<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>城市建造游戏 - 专业版</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            font-family: 'Segoe UI', 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            overflow: hidden;
            position: relative;
        }
        
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                radial-gradient(circle at 20% 80%, rgba(255,255,255,0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(255,255,255,0.05) 0%, transparent 50%);
            z-index: -1;
        }
        
        .game-container {
            width: 100vw;
            height: 100vh;
            display: flex;
            flex-direction: column;
            position: relative;
        }
        
        /* 导航栏样式 */
        .nav-bar {
            background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
            height: 60px;
            display: flex;
            align-items: center;
            padding: 0 15px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            border-bottom: 3px solid #3498db;
            position: relative;
            z-index: 10;
        }
        
        .nav-title {
            color: #ecf0f1;
            font-size: 1.2em;
            font-weight: bold;
            margin-right: 20px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        
        .nav-buttons {
            display: flex;
            gap: 5px;
            flex: 1;
            overflow-x: auto;
            padding: 5px 0;
            scrollbar-width: thin;
            scrollbar-color: #3498db #1a252f;
        }
        
        .nav-buttons::-webkit-scrollbar {
            height: 4px;
        }
        
        .nav-buttons::-webkit-scrollbar-track {
            background: #1a252f;
        }
        
        .nav-buttons::-webkit-scrollbar-thumb {
            background: #3498db;
            border-radius: 2px;
        }
        
        .nav-btn {
            min-width: 50px;
            height: 50px;
            border: none;
            background: #34495e;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            flex-shrink: 0;
        }
        
        .nav-btn:hover {
            background: #4a6572;
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.2);
        }
        
        .nav-btn.active {
            background: #3498db;
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(52, 152, 219, 0.3);
        }
        
        .nav-btn.active::after {
            content: '';
            position: absolute;
            bottom: -3px;
            left: 10%;
            width: 80%;
            height: 3px;
            background: #ecf0f1;
            border-radius: 2px;
        }
        
        .nav-img {
            width: 32px;
            height: 32px;
            pointer-events: none;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-left: auto;
        }
        
        .action-btn {
            min-width: 80px;
            height: 40px;
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
            border: none;
            border-radius: 6px;
            color: white;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            transition: all 0.2s;
            padding: 0 12px;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(39, 174, 96, 0.3);
        }
        
        .action-btn.export {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        }
        
        .action-btn.export:hover {
            box-shadow: 0 6px 12px rgba(231, 76, 60, 0.3);
        }
        
        /* 地图容器样式 */
        .map-container {
            flex: 1;
            overflow: auto;
            position: relative;
            padding: 10px;
            background: rgba(26, 37, 47, 0.95);
        }
        
        .map-grid {
            display: grid;
            grid-template-columns: repeat(50, 1fr);
            grid-template-rows: repeat(50, 1fr);
            gap: 1px;
            width: fit-content;
            margin: 0 auto;
            background: rgba(255,255,255,0.05);
            border: 2px solid rgba(255,255,255,0.1);
            box-shadow: 0 10px 40px rgba(0,0,0,0.5);
        }
        
        .map-cell {
            width: 30px;
            height: 30px;
            border: 1px solid rgba(255,255,255,0.05);
            background: rgba(52, 73, 94, 0.8);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.15s ease;
            position: relative;
            overflow: hidden;
        }
        
        .map-cell:hover {
            background: rgba(74, 101, 114, 0.9);
            border-color: rgba(52, 152, 219, 0.5);
            transform: scale(1.05);
            z-index: 1;
        }
        
        .map-cell.road {
            background: rgba(44, 62, 80, 0.9);
        }
        
        .map-cell.house {
            background: rgba(39, 174, 96, 0.2);
        }
        
        .map-cell.commercial {
            background: rgba(52, 152, 219, 0.2);
        }
        
        .map-cell.industrial {
            background: rgba(155, 89, 182, 0.2);
        }
        
        .map-cell.park {
            background: rgba(241, 196, 15, 0.2);
        }
        
        .cell-img {
            width: 24px;
            height: 24px;
            pointer-events: none;
            filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
            transition: transform 0.2s ease;
        }
        
        .map-cell:hover .cell-img {
            transform: scale(1.1);
        }
        
        /* 状态指示器 */
        .status-indicator {
            position: fixed;
            top: 70px;
            right: 20px;
            background: rgba(26, 37, 47, 0.9);
            border: 2px solid #3498db;
            border-radius: 10px;
            padding: 12px;
            color: white;
            font-size: 0.9em;
            box-shadow: 0 6px 20px rgba(0,0,0,0.4);
            z-index: 100;
            backdrop-filter: blur(10px);
            min-width: 200px;
        }
        
        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            padding-bottom: 8px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .status-item:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
        }
        
        .status-label {
            color: #bdc3c7;
        }
        
        .status-value {
            color: #ecf0f1;
            font-weight: bold;
            font-size: 1.1em;
        }
        
        /* 提示消息 */
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #27ae60;
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1000;
            max-width: 300px;
        }
        
        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }
        
        .toast.error {
            background: #e74c3c;
        }
        
        /* 文件输入 */
        .file-input {
            display: none;
        }
        
        /* 加载遮罩 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }
        
        .loading-overlay.show {
            opacity: 1;
            visibility: visible;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid rgba(255,255,255,0.1);
            border-radius: 50%;
            border-top-color: #3498db;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 响应式调整 */
        @media (max-width: 1200px) {
            .map-cell {
                width: 25px;
                height: 25px;
            }
            
            .cell-img {
                width: 20px;
                height: 20px;
            }
        }
        
        @media (max-width: 768px) {
            .nav-bar {
                height: auto;
                padding: 10px;
                flex-wrap: wrap;
            }
            
            .nav-title {
                width: 100%;
                margin-bottom: 10px;
                text-align: center;
            }
            
            .nav-buttons {
                order: 3;
                width: 100%;
                margin-top: 10px;
            }
            
            .action-buttons {
                order: 2;
                margin-left: 0;
            }
            
            .map-cell {
                width: 22px;
                height: 22px;
            }
            
            .cell-img {
                width: 18px;
                height: 18px;
            }
        }
        
        @media (max-width: 480px) {
            .map-cell {
                width: 18px;
                height: 18px;
            }
            
            .cell-img {
                width: 14px;
                height: 14px;
            }
            
            .nav-btn {
                min-width: 45px;
                height: 45px;
            }
            
            .nav-img {
                width: 28px;
                height: 28px;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <!-- 顶部导航栏 -->
        <div class="nav-bar">
            <div class="nav-title">🏗️ 城市建造者</div>
            
            <div class="nav-buttons">
                <!-- 空白按钮 -->
                <button class="nav-btn active" data-type="empty" title="清除/空地">
                    <img src="pgame/icons/empty.png" alt="空白" class="nav-img">
                </button>
                
                <!-- 道路按钮 -->
                <button class="nav-btn" data-type="road" title="道路">
                    <img src="pgame/icons/road.png" alt="道路" class="nav-img">
                </button>
                
                <!-- 居住区按钮 -->
                <button class="nav-btn" data-type="house" title="居住区">
                    <img src="pgame/icons/house.png" alt="居住区" class="nav-img">
                </button>
                
                <!-- 商业区按钮 -->
                <button class="nav-btn" data-type="commercial" title="商业区">
                    <img src="pgame/icons/commercial.png" alt="商业区" class="nav-img">
                </button>
                
                <!-- 工业区按钮 -->
                <button class="nav-btn" data-type="industrial" title="工业区">
                    <img src="pgame/icons/industrial.png" alt="工业区" class="nav-img">
                </button>
                
                <!-- 公园按钮 -->
                <button class="nav-btn" data-type="park" title="公园">
                    <img src="pgame/icons/park.png" alt="公园" class="nav-img">
                </button>
            </div>
            
            <div class="action-buttons">
                <button class="action-btn import" onclick="document.getElementById('importFile').click()">
                    📤 导入
                </button>
                <button class="action-btn export" onclick="exportGame()">
                    📥 导出
                </button>
            </div>
        </div>
        
        <!-- 地图容器 -->
        <div class="map-container">
            <div class="map-grid" id="mapGrid">
                <!-- 50x50的地图网格将由JavaScript动态生成 -->
            </div>
        </div>
        
        <!-- 状态指示器 -->
        <div class="status-indicator">
            <div class="status-item">
                <span class="status-label">当前模式:</span>
                <span class="status-value" id="currentMode">空白</span>
            </div>
            <div class="status-item">
                <span class="status-label">单元格:</span>
                <span class="status-value" id="cellCount">0</span>
            </div>
            <div class="status-item">
                <span class="status-label">文件:</span>
                <span class="status-value" id="fileName">未加载</span>
            </div>
        </div>
    </div>
    
    <!-- 提示消息 -->
    <div class="toast" id="toast"></div>
    
    <!-- 文件输入 -->
    <input type="file" id="importFile" class="file-input" accept=".json" onchange="importGame(event)">
    
    <!-- 加载遮罩 -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>
    
    <script>
        // ==================== 游戏配置 ====================
        const CONFIG = {
            MAP_SIZE: 50,           // 地图大小 (50x50)
            BUILDING_TYPES: {
                'empty': { name: '空白', class: '', icon: 'empty.png' },
                'road': { name: '道路', class: 'road', icon: 'road.png' },
                'house': { name: '住宅', class: 'house', icon: 'house.png' },
                'commercial': { name: '商业', class: 'commercial', icon: 'commercial.png' },
                'industrial': { name: '工业', class: 'industrial', icon: 'industrial.png' },
                'park': { name: '公园', class: 'park', icon: 'park.png' }
            },
            DEFAULT_MODE: 'empty'
        };
        
        // ==================== 游戏状态 ====================
        let gameState = {
            currentMode: CONFIG.DEFAULT_MODE,
            mapData: {},
            fileName: '未保存',
            selectedCell: null,
            lastSaveTime: null
        };
        
        // ==================== DOM元素缓存 ====================
        const elements = {
            mapGrid: document.getElementById('mapGrid'),
            currentMode: document.getElementById('currentMode'),
            cellCount: document.getElementById('cellCount'),
            fileName: document.getElementById('fileName'),
            toast: document.getElementById('toast'),
            loadingOverlay: document.getElementById('loadingOverlay'),
            importFile: document.getElementById('importFile')
        };
        
        // ==================== 初始化函数 ====================
        function initGame() {
            console.log('初始化城市建造游戏...');
            
            // 1. 初始化地图网格
            initMapGrid();
            
            // 2. 初始化导航按钮事件
            initNavButtons();
            
            // 3. 加载初始游戏数据
            loadInitialData();
            
            // 4. 初始化自动保存
            initAutoSave();
            
            console.log('游戏初始化完成');
        }
        
        function initMapGrid() {
            elements.mapGrid.innerHTML = '';
            
            // 设置网格样式
            elements.mapGrid.style.gridTemplateColumns = `repeat(${CONFIG.MAP_SIZE}, 1fr)`;
            elements.mapGrid.style.gridTemplateRows = `repeat(${CONFIG.MAP_SIZE}, 1fr)`;
            
            // 创建50x50的网格
            for (let y = 0; y < CONFIG.MAP_SIZE; y++) {
                for (let x = 0; x < CONFIG.MAP_SIZE; x++) {
                    const cell = createMapCell(x, y);
                    elements.mapGrid.appendChild(cell);
                    
                    // 初始化地图数据
                    const key = `${x},${y}`;
                    gameState.mapData[key] = { type: 'empty', x, y };
                }
            }
            
            updateCellCount();
        }
        
        function createMapCell(x, y) {
            const cell = document.createElement('button');
            cell.className = 'map-cell';
            cell.dataset.x = x;
            cell.dataset.y = y;
            cell.title = `坐标: (${x}, ${y})`;
            
            // 创建图片元素
            const img = document.createElement('img');
            img.className = 'cell-img';
            img.src = `pgame/icons/${CONFIG.BUILDING_TYPES.empty.icon}`;
            img.alt = '空白';
            
            cell.appendChild(img);
            
            // 添加点击事件
            cell.addEventListener('click', () => handleCellClick(x, y));
            
            // 添加鼠标悬停效果
            cell.addEventListener('mouseenter', () => {
                cell.style.borderColor = 'rgba(52, 152, 219, 0.7)';
                cell.style.zIndex = '2';
            });
            
            cell.addEventListener('mouseleave', () => {
                if (!gameState.selectedCell || 
                    !(gameState.selectedCell.x === x && gameState.selectedCell.y === y)) {
                    cell.style.borderColor = 'rgba(255,255,255,0.05)';
                    cell.style.zIndex = '';
                }
            });
            
            return cell;
        }
        
        function initNavButtons() {
            const navButtons = document.querySelectorAll('.nav-btn');
            
            navButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 移除所有按钮的active类
                    navButtons.forEach(btn => btn.classList.remove('active'));
                    
                    // 为当前按钮添加active类
                    this.classList.add('active');
                    
                    // 更新当前模式
                    const type = this.dataset.type;
                    gameState.currentMode = type;
                    
                    // 更新状态显示
                    elements.currentMode.textContent = CONFIG.BUILDING_TYPES[type].name;
                    
                    showToast(`切换到: ${CONFIG.BUILDING_TYPES[type].name}模式`);
                });
            });
            
            // 默认选中空白按钮
            document.querySelector('.nav-btn.active').click();
        }
        
        // ==================== 游戏逻辑函数 ====================
        function handleCellClick(x, y) {
            const key = `${x},${y}`;
            const type = gameState.currentMode;
            
            // 更新地图数据
            gameState.mapData[key] = { 
                type: type, 
                x: x, 
                y: y,
                timestamp: Date.now()
            };
            
            // 更新单元格显示
            updateCellDisplay(x, y, type);
            
            // 更新选中状态
            updateSelectedCell(x, y);
            
            // 更新计数
            updateCellCount();
        }
        
        function updateCellDisplay(x, y, type) {
            const cell = elements.mapGrid.querySelector(`[data-x="${x}"][data-y="${y}"]`);
            if (!cell) return;
            
            // 更新单元格类名
            cell.className = 'map-cell';
            const buildingType = CONFIG.BUILDING_TYPES[type];
            if (buildingType.class) {
                cell.classList.add(buildingType.class);
            }
            
            // 更新图片
            const img = cell.querySelector('.cell-img');
            img.src = `pgame/icons/${buildingType.icon}`;
            img.alt = buildingType.name;
            
            // 更新标题
            cell.title = `${buildingType.name} - 坐标: (${x}, ${y})`;
        }
        
        function updateSelectedCell(x, y) {
            // 移除之前选中单元格的样式
            if (gameState.selectedCell) {
                const prevCell = elements.mapGrid.querySelector(
                    `[data-x="${gameState.selectedCell.x}"][data-y="${gameState.selectedCell.y}"]`
                );
                if (prevCell) {
                    prevCell.style.borderColor = 'rgba(255,255,255,0.05)';
                    prevCell.style.transform = 'scale(1)';
                }
            }
            
            // 更新选中状态
            gameState.selectedCell = { x, y };
            
            // 添加选中样式
            const cell = elements.mapGrid.querySelector(`[data-x="${x}"][data-y="${y}"]`);
            if (cell) {
                cell.style.borderColor = '#3498db';
                cell.style.borderWidth = '2px';
                cell.style.transform = 'scale(1.05)';
            }
        }
        
        function updateCellCount() {
            const counts = {
                empty: 0,
                road: 0,
                house: 0,
                commercial: 0,
                industrial: 0,
                park: 0
            };
            
            // 统计每种类型的数量
            Object.values(gameState.mapData).forEach(cell => {
                counts[cell.type] = (counts[cell.type] || 0) + 1;
            });
            
            // 计算非空白单元格数量
            const nonEmptyCount = CONFIG.MAP_SIZE * CONFIG.MAP_SIZE - counts.empty;
            
            elements.cellCount.textContent = `${nonEmptyCount}/${CONFIG.MAP_SIZE * CONFIG.MAP_SIZE}`;
        }
        
        // ==================== 导入导出函数 ====================
        function exportGame() {
            showLoading(true);
            
            try {
                // 准备导出数据
                const exportData = {
                    version: '1.0',
                    mapSize: CONFIG.MAP_SIZE,
                    timestamp: new Date().toISOString(),
                    cells: []
                };
                
                // 收集所有非空单元格
                Object.values(gameState.mapData).forEach(cell => {
                    if (cell.type !== 'empty') {
                        exportData.cells.push({
                            x: cell.x,
                            y: cell.y,
                            type: cell.type,
                            timestamp: cell.timestamp || Date.now()
                        });
                    }
                });
                
                // 创建JSON字符串
                const jsonString = JSON.stringify(exportData, null, 2);
                
                // 创建Blob并下载
                const blob = new Blob([jsonString], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                
                // 生成文件名
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const filename = `city_builder_${timestamp}.json`;
                
                // 创建下载链接
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                
                // 清理URL
                setTimeout(() => URL.revokeObjectURL(url), 100);
                
                // 更新状态
                gameState.fileName = filename;
                elements.fileName.textContent = filename;
                
                showToast(`游戏已导出: ${filename}`);
                
            } catch (error) {
                console.error('导出失败:', error);
                showToast('导出失败: ' + error.message, true);
            } finally {
                showLoading(false);
            }
        }
        
        function importGame(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            showLoading(true);
            
            const reader = new FileReader();
            
            reader.onload = function(e) {
                try {
                    const data = JSON.parse(e.target.result);
                    
                    // 验证数据格式
                    if (!data.version || !data.mapSize || !Array.isArray(data.cells)) {
                        throw new Error('无效的游戏文件格式');
                    }
                    
                    // 检查地图大小是否匹配
                    if (data.mapSize !== CONFIG.MAP_SIZE) {
                        if (!confirm(`导入的地图大小(${data.mapSize}x${data.mapSize})与当前设置(${CONFIG.MAP_SIZE}x${CONFIG.MAP_SIZE})不匹配。是否继续导入？`)) {
                            showLoading(false);
                            return;
                        }
                    }
                    
                    // 重置地图数据
                    resetMapData();
                    
                    // 导入单元格数据
                    data.cells.forEach(cell => {
                        const x = parseInt(cell.x);
                        const y = parseInt(cell.y);
                        const type = cell.type;
                        
                        // 检查坐标是否有效
                        if (x >= 0 && x < CONFIG.MAP_SIZE && y >= 0 && y < CONFIG.MAP_SIZE) {
                            const key = `${x},${y}`;
                            gameState.mapData[key] = {
                                type: type,
                                x: x,
                                y: y,
                                timestamp: cell.timestamp || Date.now()
                            };
                            
                            // 更新显示
                            updateCellDisplay(x, y, type);
                        }
                    });
                    
                    // 更新状态
                    gameState.fileName = file.name;
                    elements.fileName.textContent = file.name;
                    
                    // 更新计数
                    updateCellCount();
                    
                    showToast(`游戏已导入: ${file.name}`);
                    
                    // 重置文件输入
                    elements.importFile.value = '';
                    
                } catch (error) {
                    console.error('导入失败:', error);
                    showToast('导入失败: ' + error.message, true);
                } finally {
                    showLoading(false);
                }
            };
            
            reader.onerror = function() {
                showToast('读取文件失败', true);
                showLoading(false);
            };
            
            reader.readAsText(file);
        }
        
        function resetMapData() {
            // 重置所有单元格为空白
            for (let y = 0; y < CONFIG.MAP_SIZE; y++) {
                for (let x = 0; x < CONFIG.MAP_SIZE; x++) {
                    const key = `${x},${y}`;
                    gameState.mapData[key] = { type: 'empty', x, y };
                    updateCellDisplay(x, y, 'empty');
                }
            }
        }
        
        // ==================== 辅助函数 ====================
        function loadInitialData() {
            // 这里可以添加从本地存储加载数据的功能
            // 暂时留空，用户可以通过导入功能加载数据
        }
        
        function initAutoSave() {
            // 每30秒自动保存到本地存储
            setInterval(() => {
                try {
                    const saveData = {
                        mapData: gameState.mapData,
                        currentMode: gameState.currentMode,
                        timestamp: Date.now()
                    };
                    
                    localStorage.setItem('cityBuilder_autoSave', JSON.stringify(saveData));
                    gameState.lastSaveTime = new Date().toISOString();
                    
                } catch (error) {
                    console.warn('自动保存失败:', error);
                }
            }, 30000);
            
            // 尝试加载自动保存的数据
            try {
                const savedData = localStorage.getItem('cityBuilder_autoSave');
                if (savedData) {
                    const data = JSON.parse(savedData);
                    const confirmLoad = confirm('检测到自动保存的数据，是否加载？');
                    
                    if (confirmLoad) {
                        // 恢复数据
                        if (data.mapData) {
                            Object.entries(data.mapData).forEach(([key, cell]) => {
                                if (cell && cell.type && cell.type !== 'empty') {
                                    gameState.mapData[key] = cell;
                                    updateCellDisplay(cell.x, cell.y, cell.type);
                                }
                            });
                        }
                        
                        if (data.currentMode) {
                            gameState.currentMode = data.currentMode;
                            elements.currentMode.textContent = CONFIG.BUILDING_TYPES[data.currentMode].name;
                            
                            // 更新导航按钮状态
                            document.querySelectorAll('.nav-btn').forEach(btn => {
                                btn.classList.remove('active');
                                if (btn.dataset.type === data.currentMode) {
                                    btn.classList.add('active');
                                }
                            });
                        }
                        
                        updateCellCount();
                        showToast('自动保存的数据已恢复');
                    }
                }
            } catch (error) {
                console.warn('加载自动保存数据失败:', error);
            }
        }
        
        function showToast(message, isError = false) {
            elements.toast.textContent = message;
            elements.toast.className = 'toast';
            
            if (isError) {
                elements.toast.classList.add('error');
            }
            
            elements.toast.classList.add('show');
            
            setTimeout(() => {
                elements.toast.classList.remove('show');
            }, 3000);
        }
        
        function showLoading(show) {
            if (show) {
                elements.loadingOverlay.classList.add('show');
            } else {
                elements.loadingOverlay.classList.remove('show');
            }
        }
        
        // ==================== 键盘快捷键 ====================
        document.addEventListener('keydown', function(event) {
            switch(event.key) {
                case '1':
                    document.querySelector('.nav-btn[data-type="empty"]').click();
                    break;
                case '2':
                    document.querySelector('.nav-btn[data-type="road"]').click();
                    break;
                case '3':
                    document.querySelector('.nav-btn[data-type="house"]').click();
                    break;
                case '4':
                    document.querySelector('.nav-btn[data-type="commercial"]').click();
                    break;
                case '5':
                    document.querySelector('.nav-btn[data-type="industrial"]').click();
                    break;
                case '6':
                    document.querySelector('.nav-btn[data-type="park"]').click();
                    break;
                case 'Escape':
                    if (gameState.selectedCell) {
                        updateSelectedCell(-1, -1);
                    }
                    break;
                case 's':
                case 'S':
                    if (event.ctrlKey || event.metaKey) {
                        event.preventDefault();
                        exportGame();
                    }
                    break;
            }
        });
        
        // ==================== 窗口事件 ====================
        window.addEventListener('beforeunload', function(event) {
            // 检查是否有未保存的更改
            const nonEmptyCells = Object.values(gameState.mapData).filter(cell => cell.type !== 'empty').length;
            
            if (nonEmptyCells > 0) {
                const message = '您有未保存的更改，确定要离开吗？';
                event.returnValue = message;
                return message;
            }
        });
        
        // ==================== 初始化游戏 ====================
        window.addEventListener('DOMContentLoaded', initGame);
    </script>
</body>
</html>
